import { format } from '../util'
export default class Parser {
    constructor (view, resolver = null, fn = '') {
        this.view = view
        this.fn = fn
        this.resolver = resolver
    }
    setResolver (resolver) {
        this.resolver = resolver
    }
    parse () {
        let s2s = (s) => {
            return '"' + s.replace(/\"|\'/g,'\\"').replace(/\s+/g,'') + '"';
        }
        if (!this.view || format(this.view) == '') return
        let codes = this.view.match(/\{{2}[^\{]+\}{2}/g);
        if (!codes) {
            return new Function('return ' +  s2s(this.view))
        }
        let contents = this.view.split(/\{{2}[^\{]+\}{2}/);
        let res = ''
        for (let i = 0,len = codes.length; i < len; i++) {
            let code = codes[i]
            res += ' + ' + s2s(contents[i]) + '+ ' + this.resolver.resolve(code)
        }
        res += ' + ' + s2s(contents[codes.length]) + ';'
        let $code = '\nlet $out = \'\'\ntry{\n$out = $out' + res + '\n}catch(e){\nconsole.error(\'' + s2s(this.view) + '====解析错误\'\n + e.name + \':\' + e.message)\n return ' + s2s(this.view.replace(/\{{2}[^\{]+\}{2}/g,''))+ '\n}\nreturn $out\n'
        return new Function(this.fn + $code)
    }

}